<template>
  <el-card>
    <el-steps :active="active"
              finish-status="success">
      <el-step title="基本信息配置"/>
      <el-step title="同步源端配置"/>
      <el-step title="目标端配置"/>
      <el-step title="映射转换配置"/>
      <el-step title="配置确认提交"/>
    </el-steps>

    <el-form :model="updateAPIForm"
             status-icon
             :rules="rules"
             ref="updateAPIForm">

      <div v-show="active == 1" class="common-top">
        <el-form-item label="api任务名称"
                      label-width="100px"
                      :required=true
                      prop="name"
                      style="width:65%">
          <el-input v-model="updateAPIForm.name"
                    auto-complete="off"
                    placeholder="请输入任务名称"
                    style="width:50%"></el-input>
          <label
              class="tips-style block">请输入任务名称，只能以字母、数字为开头，包含字母、数字和._-，3-100个字符</label>
        </el-form-item>
        <el-form-item label="描述"
                      label-width="100px"
                      prop="description"
                      style="width:65%">
          <el-input v-model="updateAPIForm.description"
                    type="textarea"
                    :rows="3"
                    auto-complete="off"
                    placeholder="请输入任务描述"
                    style="width:50%"></el-input>
        </el-form-item>
        <el-form-item label="集成模式"
                      label-width="100px"
                      :required=true
                      prop="scheduleMode"
                      style="width:65%">
          <el-input v-model="updateAPIForm.scheduleMode" v-if="false"></el-input>
          <el-radio-group v-model="updateAPIForm.scheduleModeTemp" size="mini" @change="scheduleModeUpdate">
            <el-radio-button value="MANUAL" label="手动调度"></el-radio-button>
            <el-radio-button value="SYSTEM_SCHEDULED" label="系统调度"></el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="执行周期"
                      label-width="100px"
                      style="width:65%"
                      :required="true"
                      v-if="updateAPIForm.scheduleMode=='SYSTEM_SCHEDULED'">
          <el-select v-model="updateAPIForm.cronExpression"
                     filterable
                     allow-update>
            <el-option label="每5分钟执行1次"
                       value="0 0/5 * * * ? *"></el-option>
            <el-option label="每30分钟执行1次"
                       value="0 0/30 * * * ? *"></el-option>
            <el-option label="每1小时执行1次"
                       value="0 0 0/1 * * ? *"></el-option>
            <el-option label="每2小时执行1次"
                       value="0 0 0/2 * * ? *"></el-option>
            <el-option label="每8小时执行1次"
                       value="0 0 0/8 * * ? *"></el-option>
            <el-option label="每12小时执行1次"
                       value="0 0 0/12 * * ? *"></el-option>
            <el-option label="每日0时执行1次"
                       value="0 0 0 1/1 * ? *"></el-option>
          </el-select>
          <label
              class="tips-style block">执行周期为CRON表达式，即可以选择以下内置的周期，也可以自行输入或粘贴合法的CRON表达式(最小间隔时间为2分钟)。</label>
        </el-form-item>
      </div>
      <div v-show="active == 2" class="common-top">
        <el-row :gutter="20">
          <el-col :span="10" class="grid-content ep-bg-purple">
            <div class="grid-content ep-bg-purple"/>
            <el-form-item label="接口名称"
                          label-width="100px"
                          :required=true
                          prop="apiName"
                          style="width:65%">
              <el-input v-model="updateAPIForm.apiName"
                        auto-complete="off"
                        placeholder="请输入接口名称"
                        style="width:80%"></el-input>
            </el-form-item>
            <el-form-item label="接口地址"
                          label-width="100px"
                          :required=true
                          prop="apiURL"
                          style="width:65%">
              <el-input v-model="updateAPIForm.apiURL"
                        auto-complete="off"
                        placeholder="请输入接口地址"
                        style="width:80%"></el-input>
            </el-form-item>
            <el-form-item label="请求方式"
                          label-width="100px"
                          prop="requestMethod"
                          style="width:65%">
              <el-select v-model="updateAPIForm.requestMethod" placeholder="请选择">
                <el-option v-for="item in this.apiOptions"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="请求超时时间(默认60)"
                          label-width="100px"
                          prop="requestTime"
                          style="width:65%">
              <el-input v-model="updateAPIForm.requestTime"
                        auto-complete="off"
                        style="width:80%"></el-input>
            </el-form-item>
            <el-form-item label="Json对象"
                          label-width="100px"
                          style="width:65%">
              <el-input v-model="updateAPIForm.apiJsonRoot"
                        auto-complete="off"
                        placeholder="请输入位置的key"
                        style="width:80%"></el-input>
              <label
                  class="tips-style block">例如：{data:[]}，请输入data，没有请不要输入 </label>
            </el-form-item>
            <el-form-item label="Json对象位置"
                          label-width="100px"
                          style="width:65%">
              <el-input v-model="updateAPIForm.apiJsonPosition"
                        auto-complete="off"
                        placeholder="请输入Json对象的位置"
                        style="width:80%"></el-input>
              <label
                  class="tips-style block">例如：{data:[]}，取第一个data，请输入1 </label>
            </el-form-item>
            <el-form-item label="操作"
                          label-width="100px"
                          style="width:65%">
              <el-button type="primary"
                         @click="testHttpRequest">
                发送请求
              </el-button>
            </el-form-item>
          </el-col>
          <el-col :span="14" class="grid-content ep-bg-purple">
            <div class="grid-content ep-bg-purple"/>
            <el-radio-group v-model="tabEventList.tabPosition" @change="handleChange" style="margin-bottom: 30px;">
              <el-radio-button label="Header">Header</el-radio-button>
              <el-radio-button label="URLParams">URLParams</el-radio-button>
              <el-radio-button label="Body">Body</el-radio-button>
              <el-radio-button label="Result">Result</el-radio-button>
            </el-radio-group>
            <el-tabs :tab-position="tabEventList.tabPosition" v-if="apiHeader.showTabs" style="height: 300px;">
              <el-tab-pane label="列表模式">
                <!--                动态表格-->
                <el-form-item>
                  <el-table :data="apiHeader.listMembers" :border=true style="width: 100%;">
                    <el-table-column type="index" label="字段名称" width="200">
                      <template v-slot:default="scope">
                        <el-input size="small" v-model="scope.row.keyName"
                                  placeholder="请输入字段名"></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column prop="name" label="字段值" width="200">
                      <template v-slot:default="scope">
                        <el-input autocomplete="off" size="small" v-model="scope.row.valueName"
                                  placeholder="请输入字段值"></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" width="140">
                      <template v-slot:default="scope">
                        <el-button size="mini" type="danger" plain @click="delListHeaderItem(scope.$index, scope.row)">
                          删除
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                  <i class="el-icon-circle-plus-outline" @click="addListHeaderItem"></i>
                </el-form-item>
                <!--                动态表格end-->
              </el-tab-pane>
            </el-tabs>
            <el-tabs :tab-position="tabEventList.tabPosition" v-if="apiURLParams.showTabs" style="height: 300px;">
              <el-tab-pane label="列表模式">
                <!--                动态表格-->
                <el-form-item>
                  <el-table :data="apiURLParams.listMembers" :border=true style="width: 100%;">
                    <el-table-column type="index" label="字段名称" width="200">
                      <template v-slot:default="scope">
                        <el-input autocomplete="off" size="small" v-model="scope.row.keyName"
                                  placeholder="请输入字段名"></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column prop="name" label="字段值" width="200">
                      <template v-slot:default="scope">
                        <el-input autocomplete="off" size="small" v-model="scope.row.valueName"
                                  placeholder="请输入字段值"></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" width="140">
                      <template v-slot:default="scope">
                        <el-button size="mini" type="danger" plain
                                   @click="delListURLParamsItem(scope.$index, scope.row)">
                          删除
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                  <i class="el-icon-circle-plus-outline" @click="addListURLParamsItem"></i>
                </el-form-item>
                <!--                动态表格end-->
              </el-tab-pane>
            </el-tabs>
            <el-tabs :tab-position="tabEventList.tabPosition" v-if="apiBody.showTabs" style="height: 300px;">
              <el-tab-pane label="JSON模式">
                <el-input
                    v-model="apiBody.listJson"
                    type="textarea"
                    :rows="10"
                    placeholder="请输入内容"
                    :disabled="false">
                </el-input>
              </el-tab-pane>
            </el-tabs>
            <el-tabs :tab-position="tabEventList.tabPosition" v-if="apiResult.showTabs" style="height: 300px;">
              <el-tab-pane label="JSON模式">
                <el-input
                    v-model="apiResult.listJson"
                    type="textarea"
                    :rows="10"
                    placeholder="请输入内容">
                </el-input>
              </el-tab-pane>
            </el-tabs>
          </el-col>
        </el-row>
      </div>
      <div v-show="active == 3" class="common-top">
        <el-form-item label="目的端数据源"
                      label-width="120px"
                      :required=true
                      prop="targetConnectionId"
                      style="width:65%">
          <el-select v-model="updateAPIForm.targetConnectionId"
                     @change="selectChangedTargetConnection"
                     placeholder="请选择">
            <el-option v-for="(item,index) in connectionNameList"
                       :key="index"
                       :label="`[${item.id}]${item.name}`"
                       :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目的端模式名"
                      label-width="120px"
                      :required=true
                      prop="targetSchema"
                      style="width:65%">
          <el-select v-model="updateAPIForm.targetSchema"
                     filterable
                     @change="selectChangedTargetTables"
                     placeholder="请选择">
            <el-option v-for="(item,index) in targetConnectionSchemas"
                       :key="index"
                       :label="item"
                       :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="表名配置"
                      label-width="120px"
                      :required=true
                      prop="targetTable"
                      style="width:65%">
          <el-select placeholder="请选择表名"
                     filterable
                     v-model="updateAPIForm.targetTable">
            <el-option v-for="(item,index) in targetSchemaTables"
                       :key="index"
                       :label="item"
                       :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="同步方式"
                      label-width="120px"
                      :required=true
                      prop="synchronizeType"
                      style="width:65%">
          <el-select placeholder="请选择同步方式"
                     v-model="updateAPIForm.synchronizeType">
            <el-option label="覆盖同步"
                       value="FullSync"></el-option>
            <el-option label="增量同步"
                       value="SomeSync"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="自动同步模式"
                      label-width="120px"
                      :required=true
                      prop="autoSyncMode"
                      style="width:65%">
          <span slot="label">
            <span style="color: red"><strong>自动同步模式</strong> </span>
          </span>
          <el-tooltip placement="top">
            <div slot="content">
              <p>
                目标端建表并同步数据：首次在目标的自动建表(存在重命表时会删除重建)并执行数据加载同步操作，再次执行时会根据是否有主键进行变化量同步；</p>
              <p>目标端只创建物理表: 每次执行时，只在目标端自动建表，存在重名表时会删除后重建；</p>
              <p>
                目标端只同步表里数据：每次执行时，目标端需要存在符合映射规则的物理表，最迟需要在执行任务前已经存在目标表；<br/>该选项通
                常适用于两端表结构一致时(或目标端字段包含源端所有的字段且字段数据类型一致)的数据同步场景</p>
            </div>
            <i class="el-icon-question"></i>
          </el-tooltip>
          <el-select v-model="updateAPIForm.autoSyncMode">
            <el-option label='目标端建表并同步数据'
                       :value=2></el-option>
            <el-option label='目标端只创建物理表'
                       :value=1></el-option>
            <el-option label='目标端只同步表里数据'
                       :value=0></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="建表字段自增"
                      label-width="120px"
                      :required=true
                      v-if=" updateAPIForm.autoSyncMode!==0 "
                      prop="targetAutoIncrement"
                      style="width:65%">
          <el-tooltip placement="top">
            <div slot="content">
              创建表时是否自动支持字段的自增；只有使用自动建表才会生效，不过前提需要两端的数据库表建表时支持指定自增字段，默认为false。
            </div>
            <i class="el-icon-question"></i>
          </el-tooltip>
          <el-select v-model="updateAPIForm.targetAutoIncrement">
            <el-option label='是'
                       :value=true></el-option>
            <el-option label='否'
                       :value=false></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="表名大小写转换"
                      label-width="130px"
                      :required=true
                      prop="tableNameCase"
                      style="width:45%">
          <el-tooltip placement="top">
            <div slot="content">
              表名大小写转换说明：先使用下面的表名映射，然后再使用这里的大小写转换，对支持大小写敏感的数据库类型有效。
            </div>
            <i class="el-icon-question"></i>
          </el-tooltip>
          <el-select v-model="updateAPIForm.tableNameCase">
            <el-option label='无转换'
                       value='NONE'></el-option>
            <el-option label='转大写'
                       value='UPPER'></el-option>
            <el-option label='转小写'
                       value='LOWER'></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="列名大小写转换"
                      label-width="130px"
                      :required=true
                      prop="columnNameCase"
                      style="width:45%">
          <el-tooltip placement="top">
            <div slot="content">
              列名大小写转换说明：先使用下面的列名映射，然后再使用这里的大小写转换，对支持大小写敏感的数据库类型有效。
            </div>
            <i class="el-icon-question"></i>
          </el-tooltip>
          <el-select v-model="updateAPIForm.columnNameCase">
            <el-option label='无转换'
                       value='NONE'></el-option>
            <el-option label='转大写'
                       value='UPPER'></el-option>
            <el-option label='转小写'
                       value='LOWER'></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据批次大小"
                      label-width="120px"
                      :required=true
                      v-if=" updateAPIForm.autoSyncMode!==1 "
                      prop="batchSize"
                      style="width:65%">
          <el-tooltip placement="top">
            <div slot="content">
              数据同步时单个批次处理的行记录总数，该值越大越占用内存空间。建议：小字段表设置为10000或20000，大字段表设置为100或500
            </div>
            <i class="el-icon-question"></i>
          </el-tooltip>
          <el-select v-model="updateAPIForm.batchSize">
            <el-option label=100
                       :value=100></el-option>
            <el-option label=500
                       :value=500></el-option>
            <el-option label=1000
                       :value=1000></el-option>
            <el-option label=5000
                       :value=5000></el-option>
            <el-option label=10000
                       :value=10000></el-option>
            <el-option label=20000
                       :value=20000></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="通道队列大小"
                      label-width="120px"
                      :required=true
                      v-if=" updateAPIForm.autoSyncMode!==1 "
                      prop="channelSize"
                      style="width:65%">
          <el-tooltip placement="top">
            <div slot="content">
              数据同步时缓存数据的通道队列大小，该值越大越占用内存空间。当源库读取快目标库写入慢时，缓存在内存中的数据最大占用空间
              = 行记录大小 × 数据批次大小 × 通道队列大小 。
            </div>
            <i class="el-icon-question"></i>
          </el-tooltip>
          <el-select v-model="updateAPIForm.channelSize">
            <el-option label=10
                       :value=10></el-option>
            <el-option label=20
                       :value=20></el-option>
            <el-option label=40
                       :value=40></el-option>
            <el-option label=60
                       :value=60></el-option>
            <el-option label=80
                       :value=80></el-option>
            <el-option label=100
                       :value=100></el-option>
            <el-option label=500
                       :value=500></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="同步操作方法"
                      label-width="120px"
                      :required=true
                      v-if=" updateAPIForm.autoSyncMode!==1 "
                      prop="targetSyncOption"
                      style="width:65%">
          <el-tooltip placement="top">
            <div slot="content">
              数据同步时包括增删改操作，这里选择配置执行INSERT、UPDATE、DELETE操作类型的方法，对首次数据加载无效，只对数据同步有效。
            </div>
            <i class="el-icon-question"></i>
          </el-tooltip>
          <el-select v-model="updateAPIForm.targetSyncOption">
            <el-option label='只同步INSERT操作'
                       value='ONLY_INSERT'></el-option>
            <el-option label='只同步UPDATE操作'
                       value='ONLY_UPDATE'></el-option>
            <el-option label='只同步INSERT和UPDATE'
                       value='INSERT_UPDATE'></el-option>
            <el-option label='只同步DELETE操作'
                       value='ONLY_DELETE'></el-option>
            <el-option label='只同步INSERT和DELETE'
                       value='INSERT_DELETE'></el-option>
            <el-option label='只同步UPDATE和DELETE'
                       value='UPDATE_DELETE'></el-option>
            <el-option label='执行所有的同步操作'
                       value='INSERT_UPDATE_DELETE'></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="同步前置执行SQL脚本"
                      label-width="160px"
                      v-if=" updateAPIForm.autoSyncMode!==1 "
                      prop="beforeSqlScripts"
                      style="width:65%">
          <el-input v-model="updateAPIForm.beforeSqlScripts"
                    type="textarea"
                    :rows="3"
                    auto-complete="off"
                    style="width: 65%"></el-input>
          <label
              class="tips-style block">数据同步写入目标端数据库前执行的SQL，多个SQL间以英文逗号分隔。使用场景如：MySQL数据库关闭外键约束
            SET FOREIGN_KEY_CHECKS
            = 0</label>
        </el-form-item>
        <el-form-item label="同步后置执行SQL脚本"
                      label-width="160px"
                      v-if=" updateAPIForm.autoSyncMode!==1 "
                      prop="afterSqlScripts"
                      style="width:65%">
          <el-input v-model="updateAPIForm.afterSqlScripts"
                    type="textarea"
                    :rows="3"
                    auto-complete="off"
                    style="width: 65%"></el-input>
          <label
              class="tips-style block">数据同步写入目标端数据库后执行的SQL，多个SQL间以英文逗号分隔。使用场景如：MySQL数据库恢复外键约束
            SET FOREIGN_KEY_CHECKS = 1</label>
        </el-form-item>
      </div>
      <div v-show="active == 4" class="common-top">
        <el-alert title="说明信息"
                  type="success">
          <p>(1) 当字段名映射规则记录为空时，代表目标表的字段名与源表名的字段名相同</p>
          <p>(2) 在字段名映射规则中，如果目标字段名为空（未填写），则代表剔除该字段（不能是主键）的同步</p>
        </el-alert>
        <el-button type="primary"
                   @click="addColumnNameMapperListRow()"
                   round>添加字段名映射
        </el-button>
        <el-button type="warning"
                   @click="previewColumnNameMapList()"
                   round>预览字段名映射
        </el-button>
        <el-table :data="updateAPIForm.columnNameMapper"
                  size="mini"
                  border
                  height="200"
                  style="width:90%;margin-top: 15px;">
          <template slot="empty">
            <span>请点击"添加字段名映射"按钮添加字段名映射关系记录</span>
          </template>
          <el-table-column label="字段名匹配的正则名"
                           width="320">
            <template v-slot:default="scope">
              <el-input v-model="scope.row.fromPattern"
                        type="string"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="替换的目标值"
                           width="320">
            <template v-slot:default="scope">
              <el-input v-model="scope.row.toValue"
                        type="string"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作"
                           width="220">
            <template v-slot:default="scope">
              <el-button size="mini"
                         type="danger"
                         @click="deleteColumnNameMapperListItem(scope.$index)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-show="active == 5" class="common-top">
        <el-descriptions size="small"
                         :column="1"
                         label-class-name="el-descriptions-item-label-class"
                         border>
          <el-descriptions-item label="任务名称">{{ updateAPIForm.name }}</el-descriptions-item>
          <el-descriptions-item label="任务描述">{{ updateAPIForm.description }}</el-descriptions-item>
          <el-descriptions-item label="调度方式">
            <span v-if="updateAPIForm.scheduleMode == 'MANUAL'">
              手动执行
            </span>
            <span v-if="updateAPIForm.scheduleMode == 'SYSTEM_SCHEDULED'">
              系统调度
            </span>
          </el-descriptions-item>
          <el-descriptions-item v-if="updateAPIForm.scheduleMode == 'SYSTEM_SCHEDULED'"
                                label="CRON表达式">{{ updateAPIForm.cronExpression }}
          </el-descriptions-item>
          <el-descriptions-item label="接口名称">{{ updateAPIForm.apiName }}
          </el-descriptions-item>
          <el-descriptions-item label="接口地址">{{ updateAPIForm.apiURL }}
          </el-descriptions-item>
          <el-descriptions-item label="请求方式">{{ updateAPIForm.requestMethod }}
          </el-descriptions-item>
          <el-descriptions-item label="目的端数据源">[{{
              updateAPIForm.targetConnectionId
            }}]{{ updateAPIForm.targetConnectionName }}
          </el-descriptions-item>
          <el-descriptions-item label="目的端schema">{{ updateAPIForm.targetSchema }}</el-descriptions-item>
          <el-descriptions-item label="目的端table">{{ updateAPIForm.targetTable }}
          </el-descriptions-item>
          <el-descriptions-item label="同步方式">
            <span v-if="updateAPIForm.synchronizeType == 'FullSync'">
              覆盖同步
            </span>
            <span v-if="updateAPIForm.synchronizeType == 'SomeSync'">
              增量同步
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="自动同步模式">
            <span v-if="updateAPIForm.autoSyncMode == 2">
              目标端建表并同步数据
            </span>
            <span v-if="updateAPIForm.autoSyncMode == 1">
              目标端只创建物理表
            </span>
            <span v-if="updateAPIForm.autoSyncMode == 0">
              目标端只同步表里数据
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="建表字段自增"
                                v-if=" updateAPIForm.autoSyncMode!==0 ">{{ updateAPIForm.targetAutoIncrement }}
          </el-descriptions-item>
          <el-descriptions-item label="表名大小写转换">
            <span v-if="updateAPIForm.tableNameCase == 'NONE'">
              无转换
            </span>
            <span v-if="updateAPIForm.tableNameCase == 'UPPER'">
              转大写
            </span>
            <span v-if="updateAPIForm.tableNameCase == 'LOWER'">
              转小写
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="列名大小写转换">
            <span v-if="updateAPIForm.columnNameCase == 'NONE'">
              无转换
            </span>
            <span v-if="updateAPIForm.columnNameCase == 'UPPER'">
              转大写
            </span>
            <span v-if="updateAPIForm.columnNameCase == 'LOWER'">
              转小写
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="数据批次大小"
                                v-if=" updateAPIForm.autoSyncMode!==1 ">{{ updateAPIForm.batchSize }}
          </el-descriptions-item>
          <el-descriptions-item label="通道队列大小"
                                v-if=" updateAPIForm.autoSyncMode!==1 ">{{ updateAPIForm.channelSize }}
          </el-descriptions-item>
          <el-descriptions-item label="同步操作方法"
                                v-if=" updateAPIForm.autoSyncMode!==1 ">{{ updateAPIForm.targetSyncOption }}
          </el-descriptions-item>
          <el-descriptions-item label="同步前置执行SQL脚本"
                                v-if=" updateAPIForm.autoSyncMode!==1 ">
            <span
                v-show="!updateAPIForm.beforeSqlScripts || updateAPIForm.beforeSqlScripts.length==0">[SQL脚本内容为空]</span>
            <span v-show="updateAPIForm.beforeSqlScripts.length>0">{{ updateAPIForm.beforeSqlScripts }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="同步后置执行SQL脚本"
                                v-if=" updateAPIForm.autoSyncMode!==1 ">
            <span
                v-show="!updateAPIForm.afterSqlScripts || updateAPIForm.afterSqlScripts.length==0">[SQL脚本内容为空]</span>
            <span v-show="updateAPIForm.afterSqlScripts.length>0">{{ updateAPIForm.afterSqlScripts }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="字段名映射规则">
            <span v-show="updateAPIForm.columnNameMapper.length==0">[映射关系为空]</span>
            <table v-if="updateAPIForm.columnNameMapper.length>0"
                   class="name-mapper-table">
              <tr>
                <th>字段名匹配的正则名</th>
                <th>替换的目标值</th>
              </tr>
              <tr v-for='(item,index) in updateAPIForm.columnNameMapper'
                  :key="index">
                <td>{{ item['fromPattern'] }}</td>
                <td>{{ item['toValue'] }}</td>
              </tr>
            </table>
          </el-descriptions-item>
        </el-descriptions>
      </div>

    </el-form>

    <el-button round
               v-if="active > 1"
               style="margin-top: 12px;margin-left: 20px"
               @click="pre">
      上一步
    </el-button>
    <el-button round
               @click="next"
               v-if="active > 0 && active < 5"
               style="margin-left: 20px">
      下一步
    </el-button>
    <el-button round
               @click="handleSave"
               v-if="active == 5">
      提交
    </el-button>

    <el-dialog v-if="active == 4"
               title="查看字段映射关系"
               :visible.sync="columnNameMapperDialogVisible"
               :showClose="false"
               :before-close="handleClose">
      <el-select @change="queryPreviewColumnNameMapperList"
                 v-model="preiveTableName"
                 placeholder="请选择">
        <el-option v-for="(item,index) in preiveSeeTableNameList"
                   :key="index"
                   :label="item"
                   :value="item"></el-option>
      </el-select>
      <el-table :header-cell-style="{background:'#eef1f6',color:'#606266'}"
                :data="columnNamesMapperData"
                size="mini"
                border>
        <el-table-column prop="originalName"
                         label="原始字段名"
                         min-width="20%"></el-table-column>
        <el-table-column prop="targetName"
                         label="目标表字段名"
                         min-width="20%"></el-table-column>
      </el-table>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="columnNameMapperDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>

  </el-card>
</template>

<script>

export default {

  data() {
    return {
      apiHeader: {
        showTabs: false,
        listMembers: []
      },
      apiURLParams: {
        showTabs: false,
        listMembers: []
      },
      apiBody: {
        showTabs: false,
        listJson: ''
      },
      apiResult: {
        showTabs: false,
        listJson: ''
      },
      apiOptions: [{
        value: 'GET',
        label: 'GET'
      }, {
        value: 'POST',
        label: 'POST'
      },
        {
          value: 'POST_FORM',
          label: 'POST_FORM'
        },
        {
          value: 'POST_JSON',
          label: 'POST_JSON'
        },
        {
          value: 'PUT',
          label: 'PUT'
        },
        {
          value: 'PATCH',
          label: 'PATCH'
        }],
      apiListTestdetail: {
        members: []
      },
      tabEventList: {
        tabPosition: 'top'
      },
      cronPopover: false,
      updateAPIForm: {
        id: 0,
        name: "",
        description: "",
        scheduleMode: "MANUAL",
        scheduleModeTemp: "手动调度",
        cronExpression: "",
        targetTable: "",
        columnNameMapper: [],
        tableNameCase: 'NONE',
        columnNameCase: 'NONE',
        targetConnectionId: '请选择',
        targetDropTable: true,
        targetOnlyupdate: false,
        targetAutoIncrement: false,
        autoSyncMode: 2,
        targetSchema: "",
        batchSize: 5000,
        channelSize: 100,
        targetSyncOption: 'INSERT_UPDATE_DELETE',
        beforeSqlScripts: '',
        afterSqlScripts: '',
        apiName: "",
        apiURL: "",
        requestMethod: 'GET',
        requestTime: "60",
        requestParams: '',
        responseResult: '',
        synchronizeType: '',
        targetConnectionName: '',
        apiJsonRoot: '',
        apiJsonPosition: ''
      },
      rules: {
        apiName: [
          {
            required: true,
            message: "接口名称不能为空",
            trigger: "blur"
          }
        ],
        apiURL: [
          {
            required: true,
            message: "请求地址不能为空",
            trigger: "blur"
          }
        ],
        name: [
          {
            required: true,
            message: "任务名称不能为空",
            trigger: "blur"
          }
        ],
        scheduleMode: [
          {
            required: true,
            type: 'string',
            message: "调度方式必须选择",
            trigger: "change"
          }
        ],
        targetConnectionId: [
          {
            required: true,
            type: 'integer',
            message: "必选选择一个目的端",
            trigger: "change"
          }
        ],
        targetSchema: [
          {
            required: true,
            type: 'string',
            message: "必选选择一个Schema名",
            trigger: "change"
          }
        ],
        targetTable: [
          {
            required: true,
            type: 'string',
            message: "必选择一个table名",
            trigger: "change"
          }
        ],
        synchronizeType: [
          {
            required: true,
            type: 'string',
            message: "同步方式必须选择",
            trigger: "change"
          }
        ],
        batchSize: [
          {
            required: true,
            type: 'integer',
            message: "必选选择一个数据批次大小",
            trigger: "change"
          }
        ],
        channelSize: [
          {
            required: true,
            type: 'integer',
            message: "必选选择一个通道队列大小",
            trigger: "change"
          }
        ],
        targetSyncOption: [
          {
            required: true,
            type: 'string',
            message: "必选选择一个同步方法来 ",
            trigger: "change"
          }
        ]
      },
      active: 1,
      targetConnection: {
        name: ''
      },
      targetConnectionSchemas: [],
      targetSchemaTables: [],
      columnNameMapperDialogVisible: false,
      tableNamesMapperData: [],
      columnNamesMapperData: [],
      preiveSeeTableNameList: [],
      preiveTableName: "",
      connectionNameList: []
    }
  },
  methods: {
    initScheduleModeTemp(val) {
      if (val === 'SYSTEM_SCHEDULED') {
        return "系统调度"
      }
      if (val === 'MANUAL') {
        return "手动调度"
      }
    },
    testHttpRequest() {
      console.log('test api starting .....')
      this.$http({
        method: "POST",
        headers: {
          'Content-Type': 'application/json'
        },
        url: "/dbswitch/admin/api/v1/api-task/testHttpRequest",
        data: JSON.stringify({
          apiURL: this.updateAPIForm.apiURL,
          requestMethod: this.updateAPIForm.requestMethod,
          apiParams: this.apiURLParams.listMembers,
          apiHeaders: this.apiHeader.listMembers,
          apiBody: this.apiBody.listJson,
          apiJsonRoot: this.updateAPIForm.apiJsonRoot,
          apiJsonPosition: this.updateAPIForm.apiJsonPosition,
        })
      }).then(res => {
        console.log('Response:', res.data);
        this.apiResult.listJson = JSON.stringify(res.data, null, 2);
        Object.keys(res.data).forEach(key => {
          let newItem = {
            fromPattern: key,
            toValue: ""
          };
          this.updateAPIForm.columnNameMapper.push(newItem);
        });
      });

    },
    loadAssignmentDetail: function () {
      this.$http.get(
          "/dbswitch/admin/api/v1/api-task/detail/id/" + this.$route.query.id
      ).then(res => {
        if (0 === res.data.code) {
          let detail = res.data.data;
          let varAutoSyncMode = 2;
          if (detail.configuration.targetDropTable && detail.configuration.targetOnlyCreate) {
            varAutoSyncMode = 1;
          } else if (!detail.configuration.targetDropTable && !detail.configuration.targetOnlyCreate) {
            varAutoSyncMode = 0;
          } else {
            varAutoSyncMode = 2;
          }
          this.updateAPIForm = {
            id: detail.id,
            name: detail.name,
            description: detail.description,
            scheduleMode: detail.scheduleMode,
            scheduleModeTemp: this.initScheduleModeTemp(detail.scheduleMode),
            cronExpression: detail.cronExpression,
            apiName: detail.configuration.apiName,
            apiURL: detail.configuration.apiURL,
            requestMethod: detail.configuration.requestMethod,
            requestTime: detail.configuration.requestTime,
            synchronizeType: detail.configuration.synchronizeType,
            apiJsonRoot: detail.configuration.apiJsonRoot,
            apiJsonPosition: detail.configuration.apiJsonPosition,
            apiParams: detail.configuration.listMembers,
            apiHeaders: detail.configuration.listMembers,
            apiBody: detail.configuration.listJson,
            targetTable: detail.configuration.targetTable,
            columnNameMapper: detail.configuration.columnNameMapper,
            tableNameCase: detail.configuration.tableNameCase,
            columnNameCase: detail.configuration.columnNameCase,
            targetConnectionId: detail.configuration.targetConnectionId,
            targetConnectionName: detail.configuration.targetConnectionName,
            targetDropTable: detail.configuration.targetDropTable,
            targetOnlyCreate: detail.configuration.targetOnlyCreate,
            targetAutoIncrement: detail.configuration.targetAutoIncrement,
            autoSyncMode: varAutoSyncMode,
            targetSchema: detail.configuration.targetSchema,
            batchSize: detail.configuration.batchSize,
            channelSize: detail.configuration.channelSize,
            targetSyncOption: detail.configuration.targetSyncOption,
            beforeSqlScripts: detail.configuration.beforeSqlScripts,
            afterSqlScripts: detail.configuration.afterSqlScripts,
          }
          this.selectChangedTargetConnection(this.updateAPIForm.targetConnectionId)
        } else {
          if (res.data.message) {
            alert("查询任务失败," + res.data.message);
          }
        }
      });
    },
    handleChange(value) {
      console.log('选中的值：', value);
      switch (value) {
        case 'Header':
          this.displayAPIHeader();
          break;
        case 'URLParams':
          this.displayUrlParamsData();
          break;
        case 'Body':
          this.displayAPIBody();
          break;
        case 'Result':
          this.displayAPIResult();
          break;
        default:
          break;
      }
    },
    displayAPIHeader() {
      this.apiHeader.showTabs = true;
      this.apiURLParams.showTabs = false;
      this.apiBody.showTabs = false;
      this.apiResult.showTabs = false;
      // this.apiHeader.listJson = this.testAPITemp.apiHeader;
    },
    displayUrlParamsData() {
      this.apiHeader.showTabs = false;
      this.apiURLParams.showTabs = true;
      this.apiBody.showTabs = false;
      this.apiResult.showTabs = false;
      // this.apiURLParams.listJson = this.testAPITemp.apiURLParams;
    },
    displayAPIBody() {
      this.apiHeader.showTabs = false;
      this.apiURLParams.showTabs = false;
      this.apiBody.showTabs = true;
      this.apiResult.showTabs = false;
      // this.apiBody.listJson = this.testAPITemp.apiBody;
    },
    displayAPIResult() {
      // 根据 `json` tab 的内容进行处理
      this.apiHeader.showTabs = false;
      this.apiURLParams.showTabs = false;
      this.apiBody.showTabs = false;
      this.apiResult.showTabs = true;
      // this.apiResult.listJson = this.testAPITemp.apiResult;
    },
    addListHeaderItem() {
      this.apiHeader.listMembers.push({
        keyName: '',
        valueName: ''
      });
    },
    delListTestItem(index, row) {
      const that = this;
      this.$confirm('确认删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        //点击确定的操作(调用接口)
        const hasmembers = that.apiListTestdetail.members;
        for (let i = 0; i < hasmembers.length; i++) {
          if (row.id === hasmembers[i].id) {
            that.apiListTestdetail.members.splice(i, 1);
          }
        }
      }).catch(() => {
      });
    },
    scheduleModeUpdate(val) {
      if (val === '系统调度') {
        this.updateAPIForm.scheduleMode = "SYSTEM_SCHEDULED"
      }
      if (val === '手动调度') {
        this.updateAPIForm.scheduleMode = "MANUAL"
      }
    },
    handleClose(done) {
    },
    next() {
      if (this.active++ > 4) this.active = 5
    },
    pre() {
      if (this.active-- < 2) this.active = 1
    },
    loadConnections: function () {
      this.connectionNameList = [];
      this.$http({
        method: "GET",
        url: "/dbswitch/admin/api/v1/connection/list/name"
      }).then(
          res => {
            if (0 === res.data.code) {
              this.connectionNameList = res.data.data;
            } else {
              if (res.data.message) {
                alert("加载任务列表失败:" + res.data.message);
                this.connectionNameList = [];
              }
            }
          },
          function () {
            console.log("failed");
          }
      );
    },
    changeupdateCronExpression: function (value) {
      this.updateAPIForm.cronExpression = value;
    },
    selectChangedTargetConnection: function (value) {
      this.targetConnection = this.connectionNameList.find(
          (item) => {
            return item.id === value;
          });

      this.targetConnectionSchemas = [];
      this.$http.get(
          "/dbswitch/admin/api/v1/connection/schemas/get/" + value
      ).then(res => {
        if (0 === res.data.code) {
          this.targetConnectionSchemas = res.data.data;
        } else {
          this.$message.error("查询目的端数据库的Schema失败," + res.data.message);
          this.targetConnectionSchemas = [];
        }
      });
    },
    selectChangedTargetTables: function (value) {
      this.targetSchemaTables = [];
      this.$http.get(
          "/dbswitch/admin/api/v1/connection/tables/get/" + this.updateAPIForm.targetConnectionId + "?schema=" + value
      ).then(res => {
        if (0 === res.data.code) {
          this.targetSchemaTables = res.data.data;
        } else {
          this.$message.error("查询目标端数据库在指定Schema下的物理表列表失败," + res.data.message);
          this.targetSchemaTables = [];
        }
      });
    },
    previewColumnNameMapList: function () {

      this.preiveSeeTableNameList = [this.updateAPIForm.targetTable];
      this.preiveTableName = "";
      this.columnNamesMapperData = [];
      this.columnNameMapperDialogVisible = true;
    },
    queryPreviewColumnNameMapperList: function () {
      if (!this.preiveTableName || this.preiveTableName.length == 0) {
        alert("请选择一个表名！");
        return;
      }

      this.$http({
        method: "POST",
        headers: {
          'Content-Type': 'application/json'
        },
        url: "/dbswitch/admin/api/v1/mapper/preview/column",
        data: JSON.stringify({
          id: this.updateAPIForm.targetConnectionId,
          schemaName: this.updateAPIForm.targetSchema,
          tableName: this.preiveTableName,
          nameMapper: this.updateAPIForm.columnNameMapper,
          columnNameCase: this.updateAPIForm.columnNameCase
        })
      }).then(res => {
        if (0 === res.data.code) {
          this.columnNamesMapperData = res.data.data;
        } else {
          if (res.data.message) {
            alert(res.data.message);
          }
        }
      });

    },
    addColumnNameMapperListRow: function () {
      this.updateAPIForm.columnNameMapper.push({"fromPattern": "", "toValue": ""});
    },
    deleteColumnNameMapperListItem: function (index) {
      this.updateAPIForm.columnNameMapper.splice(index, 1);
    },
    handleSave: function () {
      if (0 === this.updateAPIForm.autoSyncMode) {
        this.updateAPIForm.targetDropTable = false;
        this.updateAPIForm.targetOnlyupdate = false;
      } else if (1 === this.updateAPIForm.autoSyncMode) {
        this.updateAPIForm.targetDropTable = true;
        this.updateAPIForm.targetOnlyupdate = true;
      } else {
        this.updateAPIForm.targetDropTable = true;
        this.updateAPIForm.targetOnlyupdate = false;
      }
      this.$refs['updateAPIForm'].validate(valid => {
        if (valid) {
          this.$http({
            method: "POST",
            headers: {
              'Content-Type': 'application/json'
            },
            url: "/dbswitch/admin/api/v1/api-task/update",
            data: JSON.stringify({
              id: this.$route.query.id,
              name: this.updateAPIForm.name,
              description: this.updateAPIForm.description,
              scheduleMode: this.updateAPIForm.scheduleMode,
              cronExpression: this.updateAPIForm.cronExpression,
              config: {
                apiName: this.updateAPIForm.apiName,
                apiURL: this.updateAPIForm.apiURL,
                requestMethod: this.updateAPIForm.requestMethod,
                requestTime: this.updateAPIForm.requestTime,
                targetConnectionId: this.updateAPIForm.targetConnectionId,
                targetSchema: this.updateAPIForm.targetSchema,
                targetTable: this.updateAPIForm.targetTable,
                synchronizeType: this.updateAPIForm.synchronizeType,
                apiJsonRoot: this.updateAPIForm.apiJsonRoot,
                apiJsonPosition: this.updateAPIForm.apiJsonPosition,
                apiParams: this.apiURLParams.listMembers,
                apiHeaders: this.apiHeader.listMembers,
                apiBody: this.apiBody.listJson,
                columnNameMapper: this.updateAPIForm.columnNameMapper,
                tableNameCase: this.updateAPIForm.tableNameCase,
                columnNameCase: this.updateAPIForm.columnNameCase,
                targetDropTable: this.updateAPIForm.targetDropTable,
                targetOnlyupdate: this.updateAPIForm.targetOnlyupdate,
                targetAutoIncrement: this.updateAPIForm.targetAutoIncrement,
                batchSize: this.updateAPIForm.batchSize,
                channelSize: this.updateAPIForm.channelSize,
                targetSyncOption: this.updateAPIForm.targetSyncOption,
                beforeSqlScripts: this.updateAPIForm.beforeSqlScripts,
                afterSqlScripts: this.updateAPIForm.afterSqlScripts,
              }
            })
          }).then(res => {
            if (0 === res.data.code) {
              this.$message({
                message: '添加任务成功!',
                type: 'success'
              });
              this.$router.push('/apitask/assignment')
            } else {
              if (res.data.message) {
                alert(res.data.message);
              }
            }
          });
        } else {
          alert("请点击【上一步】检查输入");
        }
      });
    }
  },
  created() {
    this.loadConnections();
    this.loadAssignmentDetail();
  },
}
</script>

<style scoped>
.el-card {
  width: 100%;
  height: 100%;
  overflow: auto;
}

.tip-content {
  font-size: 12px;
}

.name-mapper-table,
.name-mapper-table table tr th,
.name-mapper-table table tr td {
  border-collapse: collapse;
  border: 1px solid #e0dddd;
  width: 100%;
}

.el-descriptions__body
.el-descriptions__table
.el-descriptions-row
.el-descriptions-item__label {
  min-width: 20px;
  max-width: 60px;
}

.tips-style {
  font-size: 12px;
  color: #a0a6b8;
}

.block {
  padding-top: 6px;
  display: block;
}

.common-top {
  margin-top: 40px;
}
</style>